<template>
  <q-form ref="form" @submit="onSubmit" class="q-gutter-md q-pb-xl">
    <formInput ref='formInput' :fieldlist="formFields" multipleCol />

    <history v-if="mode === 'edit'" class="q-mb-xl" :data="historyData" :escape="historyEscape" />

    <q-page-sticky position="bottom" :offset="[0, 28]">
      <q-btn label="保存" type="submit" color="primary" class="btn-fixed-width" icon="save" :loading="saving" v-if="canSave" />
      <q-btn label="返回" @click="onReset" color="primary" outline class="q-ml-md bg-white" />
    </q-page-sticky>
  </q-form>
</template>

<script>
import { defineComponent } from 'vue';
import formInput from 'src/components/FormInput.vue';
import { detailPageMix } from 'src/lib/mixin.js';
import history from 'src/components/history.vue'
import { useMeta } from 'quasar';
import { useStore } from 'stores/store';
import pinyin from 'src/lib/vue-py';
import moment from 'moment';
import md5 from 'md5';

export default defineComponent({
  name: 'tenantDetail',
  setup (props, context) {
    const $store = useStore();
    const modelLabel = '租户信息';
    const moduleName = 'tenant';
    const detailApi = `/c2/manager/${moduleName}/detail`; // 明细数据接口
    const createApi = `/c2/manager/${moduleName}/create`; // 新建数据接口
    const updateApi = `/c2/manager/${moduleName}/update`; // 更新数据接口

    useMeta({
      // 设置文件标题
      title: `${modelLabel}详情 - ${$store.siteConfig.appName} - 木多鱼系列`
    });

    return {
      modelLabel,
      moduleName,
      detailApi,
      createApi,
      updateApi
    }
  },
  components: {
    formInput,
    history
  },
  mixins: [detailPageMix],
  data () {
    return {
      formFields: {
        sep1: { type: 'separator', label: '基本信息' },
        tenant_name: { type: 'input', label: '组织名称 *', value: '', rules: [val => !!val || '请输入组织名称'], readonly: false },
        company: { type: 'input', label: '公司名称', value: '', readonly: false },
        link_man: { type: 'input', label: '联系人', value: '', readonly: false },
        link_phone: { type: 'input', label: '联系电话', value: '', readonly: false },
        remark: { type: 'input', label: '描述', value: '', readonly: false },
        source: { type: 'input', label: '来源', value: '', readonly: false },

        sep2: { type: 'separator', label: '地址' },
        province: { type: 'select', label: '省份', value: '', options: [], selected: [], readonly: false },
        city: { type: 'select', label: '城市', value: '', options: [], selected: [], readonly: false },
        district: { type: 'select', label: '区县', value: '', clearable: true, readonly: false },
        street: { type: 'select', label: '街道乡镇', value: '', options: [], selected: [], readonly: false },
        address: { type: 'input', label: '地址', value: '', readonly: false },
        zipcode: { type: 'input', label: '邮政编码', value: '', readonly: false },

        sep3: { type: 'separator', label: '状态', group: 'state' },
        state: { type: 'toggle', label: '状态', value: 1, trueValue: 1, trueLabel: '启用', falseValue: 0, falseLabel: '禁用', readonly: false, group: 'state' },

        sep4: { type: 'separator', label: '用户信息', group: 'user' },
        nickname: { type: 'input', label: '用户名 *', value: '', rules: [val => !!val || '请输入用户名'], hint: '请牢记用户名', group: 'user' },
        password: { type: 'input', label: '密码 *', value: '', rules: [this.checkPassword], hint: '请牢记密码', group: 'user' },
        tel: { type: 'input', label: '电话', value: '', group: 'user' }
      },
      regionData: []
    };
  },
  async created () {
    // 取地区数据
    this.regionData = await this.$idb.get('config', 'region');
    this.formFields.province.options = this.regionData.map(v => ({
      value: v.name,
      label: v.name,
      children: v.children
    }));
  },
  mounted () {
    if (this.mode === 'add') {
      for (const key in this.formFields) {
        if (this.formFields[key].group === 'state') {
          delete this.formFields[key];
        }
      }
    }
    if (this.mode === 'edit') {
      for (const key in this.formFields) {
        if (this.formFields[key].group === 'user') {
          delete this.formFields[key];
        }
      }
      this.refreshData();
    }
  },
  methods: {
    onSubmit () {
      /* const self = this;
      this.$refs.formInput.validateAll();
      this.$nextTick(() => {
        this.$refs.form.validate().then(ot => {
          if (ot) {
            self.saving = true;
            self.saveData();
          }
        });
      }); */
      this.saving = true;

      const formData = { user: {} };
      for (const field in this.formFields) {
        let fieldValue = '';
        if (this.formFields[field].type === 'select' && typeof this.formFields[field].value === 'object' && this.formFields[field].value) {
          fieldValue = this.formFields[field].value.value;
        } else {
          fieldValue = this.formFields[field].value;
        }

        if (this.formFields[field].group === 'user') {
          formData.user[field] = fieldValue;
        } else {
          formData[field] = fieldValue
        }
      }
      if (formData.user && formData.user.password) {
        formData.user.password = md5(formData.user.password); // 密码md5加密
      }

      this.saveData(formData);
    }
  },
  computed: {
  },
  watch: {
    'formFields.province.value' (val) {
      if (val) {
        const item = this.formFields.province.options.filter(v => v.value === val);
        this.formFields.city.options = item.length > 0 ? item[0].children.map(v => ({
          value: v.name,
          label: v.name,
          children: v.children
        })) : [];
      } else {
        this.formFields.city.options = [];
        this.formFields.city.selected = [];
        this.formFields.city.value = '';
      }
    },
    'formFields.city.value' (val) {
      if (val) {
        const item = this.formFields.city.options.filter(v => v.value === val);
        this.formFields.district.options = item.length > 0 ? item[0].children.map(v => ({
          value: v.name,
          label: v.name,
          children: v.children
        })) : [];
      } else {
        this.formFields.district.options = [];
        this.formFields.district.selected = [];
        this.formFields.district.value = '';
      }
    },
    'formFields.district.value' (val) {
      if (val) {
        const item = this.formFields.district.options.filter(v => v.value === val);
        this.formFields.street.options = item.length > 0 ? item[0].children.map(v => ({
          value: v.name,
          label: v.name,
          children: v.children
        })) : [];
      } else {
        this.formFields.street.options = [];
        this.formFields.street.selected = [];
        this.formFields.street.value = '';
      }
    },
    'formFields.tenant_name.value' (val) {
      if (this.mode === 'add') {
        this.formFields.nickname.value = `${pinyin.chineseToPinYin(this.formFields.tenant_name.value, true).toLowerCase()}_admin`;
        this.formFields.password.value = `${pinyin.chineseToPinYin(this.formFields.tenant_name.value, true).toLowerCase()}${moment().format('YYMMDD')}`;
      }
    }
  }
});
</script>
